<script setup>
import {ref, onBeforeMount, watchEffect, provide} from 'vue'
import {getAddrSelectOptions, getProductCategoryOptions} from "@/utils/CommonDataUtil.js";
import {getAuthorityPageAPI} from "@/api/manager.js";
import {getProductPageAPI} from "@/api/product.js";
import ProductCard from "@/views/index/product/components/ProductCard.vue";
import ProductDetail from "@/views/index/product/components/ProductDetail.vue";
import useProductStore from "@/store/modules/ProductStore.js";

// ***********
// * 输入限制 *
// ***********
const env = import.meta.env
const PRODUCT_TITLE_MAX_LEN = env.VITE_PRODUCT_TITLE_MAX_LEN
const PRODUCT_ISBN_MAX_LEN = env.VITE_PRODUCT_ISBN_MAX_LEN
const PRODUCT_ADDRESS_MAX_LEN = env.VITE_PRODUCT_ADDRESS_MAX_LEN
const PRODUCT_LABEL_NAME_MAX_LEN = env.VITE_PRODUCT_LABEL_NAME_MAX_LEN
const PRODUCT_PARAM_NAME_MAX_LEN = env.VITE_PRODUCT_PARAM_NAME_MAX_LEN
const PRODUCT_PARAM_VAL_MAX_LEN = env.VITE_PRODUCT_PARAM_VAL_MAX_LEN
const PRODUCT_OPTIOON_NAME_MAX_LEN = env.VITE_PRODUCT_OPTIOON_NAME_MAX_LEN

// ***********
// * 筛选条件 *
// ***********
const code = ref('')
const title = ref('')
const productCategoryAll = ref([])
const productCategory = ref('')
const productCategoryOptions = ref([])
const productCategorySub = ref('')
const productCategorySubDisabled = ref(false)
const productCategorySubOptions = ref([])
const chineseAllDistinguish = ref([]);
const provinceSelectVal = ref('')
const provinceSelectOptions = ref([])
const citySelectVal = ref('')
const citySelectDisabled = ref(false)
const citySelectOptions = ref([])
const distinguishSelectVal = ref('')
const distinguishSelectDisabled = ref(false)
const distinguishSelectOptions = ref([])
onBeforeMount(async () => {
  // 获取省市区数据
  await getAddrSelectOptions(chineseAllDistinguish, provinceSelectOptions)
  provinceSelectOptions.value.unshift({value: 'all', label: '全部'})
  // 获取分类数据
  await getProductCategoryOptions(productCategoryAll, productCategoryOptions)
  productCategoryOptions.value.unshift({value: -1, label: '全部'})
})
const productCategoryChange = () => {
  if (productCategory.value !== null && productCategory.value !== '' && productCategory.value !== -1) {
    productCategorySub.value = ''
    productCategorySubOptions.value = productCategoryAll.value.find(item => item.id === productCategory.value)
        .subs.map(item => ({value: item.id, label: item.name}))
    productCategorySubOptions.value.unshift({value: -1, label: '全部'})
  }
}
const provinceSelectValChange = () => {
  if (provinceSelectVal.value !== 'all' && provinceSelectVal.value.length > 0) {
    citySelectVal.value = ''
    distinguishSelectVal.value = ''
    citySelectOptions.value = chineseAllDistinguish.value.find(item => item.name === provinceSelectVal.value)
        .districtList.map(item => ({value: item.name, label: item.name}))
    citySelectOptions.value.unshift({value: 'all', label: '全部'})
  }
}
const citySelectValChange = () => {
  if (citySelectVal.value !== 'all' && citySelectVal.value.length > 0) {
    distinguishSelectVal.value = ''
    distinguishSelectOptions.value = chineseAllDistinguish.value.find(item => item.name === provinceSelectVal.value)
        .districtList.find(item => item.name === citySelectVal.value)
        .districtList.map(item => ({value: item.name, label: item.name}))
    distinguishSelectOptions.value.unshift({value: 'all', label: '全部'})
  }
}
watchEffect(() => {
  if (provinceSelectVal.value !== 'all' && provinceSelectVal.value.length > 0) {
    citySelectDisabled.value = false
  } else {
    citySelectVal.value = ''
    citySelectDisabled.value = true
    distinguishSelectVal.value = ''
    distinguishSelectDisabled.value = true
  }
  if (citySelectVal.value !== 'all' && citySelectVal.value.length > 0) {
    distinguishSelectDisabled.value = false
  } else {
    distinguishSelectVal.value = ''
    distinguishSelectDisabled.value = true
  }
  if (productCategory.value !== null && productCategory.value !== '' && productCategory.value !== -1) {
    productCategorySubDisabled.value = false
  } else {
    productCategorySub.value = ''
    productCategorySubDisabled.value = true
  }
})
const freightSelectValue = ref('')
const freightSelectOptions = [
  {label: '全部', value: ''},
  {label: '包邮', value: false},
  {label: '不包邮', value: true},
]
const isRemoveSelectValue = ref('')
const isRemoveSelectOptions = [
  {label: '全部', value: ''},
  {label: '删除', value: true},
  {label: '未删除', value: false},
]
const productLabel = ref('')
const productParamName = ref('')

// 分页数据
const current = ref(1)
const pageSize = ref(10)
const pageCnt = ref(0)
const size = ref(0)
const data = ref([])
const getProductPage = async (
    current_, pageSize_,
    title_ = null, category_ = null, categorySub_ = null, delivery_ = null, freight_ = null, label_ = null, param_ = null,
    isRemove_ = null, code_ = null
) => {
  const res = await getProductPageAPI(current_, pageSize_, title_, category_, categorySub_, delivery_, freight_, label_, param_, isRemove_, code_)
  if (res === null) return
  current.value = res.current
  pageSize.value = res.pageSize
  pageCnt.value = res.pageCnt
  size.value = res.size
  data.value = res.data
  // 缓存商品信息
  useProductStore().saveProducts(data.value)
}
// 初始查询
onBeforeMount(async () => {
  await getProductPage(current.value, pageSize.value)
})
// 条件查询
const searchByCondition = async () => {
  await getProductPage(
      current.value, pageSize.value, title.value,
      (productCategory.value === -1 ? '' : productCategory.value),
      (productCategorySub.value === -1 ? '' : productCategorySub.value),
      ((provinceSelectVal.value === 'all' ? '' : provinceSelectVal.value) +
          (citySelectVal.value === 'all' ? '' : citySelectVal.value) +
          (distinguishSelectVal.value === 'all' ? '' : distinguishSelectVal.value)),
      freightSelectValue.value, productLabel.value, productParamName.value, isRemoveSelectValue.value, code.value
  )
}

// 分页每页数据大小改变
const handlePageSizeChange = async (val) => {
  pageSize.value = val
  await searchByCondition()
}
// 当前页发生变化
const handleCurrentChange = async (val) => {
  current.value = val
  await searchByCondition()
}

// 条件清除
const clearCondition = () => {
  code.value = ''
  title.value = ''
  productCategory.value = ''
  productCategorySub.value = ''
  provinceSelectVal.value = ''
  citySelectVal.value = ''
  distinguishSelectVal.value = ''
  freightSelectValue.value = ''
  productLabel.value = ''
  productParamName.value = ''
  isRemoveSelectValue.value = ''
}

// 显示商品详情
const showProductIdx = ref(0)
const productDetailVisible = ref(false)
const showProductDetail = (productIdx) => {
  showProductIdx.value = productIdx
  productDetailVisible.value = true
}
provide('productDetail', {productDetailVisible, showProductDetail, searchByCondition})
</script>

<template>
  <div class="product-manage">
    <div class="fixed top-20 right-10">
      <div class="filter-box glass-container p-4 w-56">
        <div><span>ISBN</span></div>
        <div>
          <el-input v-model="code" placeholder="请输入书籍 ISBN" clearable show-word-limit
                    :maxlength="PRODUCT_ISBN_MAX_LEN"></el-input>
        </div>
        <div><span>商品标题</span></div>
        <div>
          <el-input v-model="title" placeholder="请输入商品标题" clearable show-word-limit
                    :maxlength="PRODUCT_TITLE_MAX_LEN"></el-input>
        </div>
        <div><span>商品分类</span></div>
        <div>
          <el-select v-model="productCategory" @change="productCategoryChange"
                     placeholder="请选择一级商品分类">
            <el-option
                v-for="item in productCategoryOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </div>
        <div>
          <el-select v-model="productCategorySub" :disabled="productCategorySubDisabled"
                     placeholder="请选择二级商品分类">
            <el-option
                v-for="item in productCategorySubOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </div>
        <div><span>商品发货地</span></div>
        <div>
          <el-select v-model="provinceSelectVal" @change="provinceSelectValChange" placeholder="省/市/自治区">
            <el-option
                v-for="item in provinceSelectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </div>
        <div>
          <el-select v-model="citySelectVal" @change="citySelectValChange" :disabled="citySelectDisabled"
                     placeholder="市">
            <el-option
                v-for="item in citySelectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </div>
        <div>
          <el-select v-model="distinguishSelectVal" :disabled="distinguishSelectDisabled" placeholder="区/县">
            <el-option
                v-for="item in distinguishSelectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </div>
        <div><span>是否包邮</span></div>
        <div>
          <el-select v-model="freightSelectValue" class="select" placeholder="是否包邮">
            <el-option
                v-for="item in freightSelectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </div>
        <div><span>商品标签</span></div>
        <div>
          <el-input v-model="productLabel" placeholder="请输入商品标签" clearable show-word-limit
                    :maxlength="PRODUCT_LABEL_NAME_MAX_LEN"></el-input>
        </div>
        <div><span>商品参数</span></div>
        <div>
          <el-input v-model="productParamName" placeholder="请输入商品参数名称" clearable show-word-limit
                    :maxlength="PRODUCT_PARAM_NAME_MAX_LEN"></el-input>
        </div>
        <div><span>是否删除</span></div>
        <div>
          <el-select v-model="isRemoveSelectValue" class="select" placeholder="是否删除">
            <el-option
                v-for="item in isRemoveSelectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </div>
        <div>
          <el-button class="w-full" type="primary" plain @click="searchByCondition">搜索</el-button>
        </div>
        <el-button class="w-full" type="info" plain @click="clearCondition">清空</el-button>
      </div>
    </div>
    <div class="fixed bottom-2 right-6 z-10 glass-container p-2 flex justify-end items-center">
      <el-pagination
          v-model:current-page="current"
          v-model:page-size="pageSize"
          :page-sizes="[1, 5, 10, 20, 30, 40]"
          :page-count="pageCnt"
          layout="sizes, prev, pager, next, jumper"
          @size-change="handlePageSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
    <div class="product-card-box glass-container w-5/6 ml-2 pt-8">
      <ProductCard v-for="(item, idx) in data" :product="item" :productIdx="idx"></ProductCard>
    </div>
    <ProductDetail :product="data[showProductIdx]"></ProductDetail>
  </div>
</template>

<style scoped lang="scss">
.product-manage {
  .filter-box {
    & > div {
      margin-bottom: 0.5rem;

      &:last-child {
        margin-bottom: 0;
      }

      & > span {
        color: #f4f4f5;
        font-size: 0.8rem;
        font-weight: bold;
      }
    }
  }

  .product-card-box {
    display: grid;
    // 列数自动填充，列宽最小为 24rem，最大占1份平均grid容器宽度
    grid-template-columns: repeat(auto-fill, minmax(24rem, 1fr));
    grid-auto-flow: row; // 容器元素按顺序自动放置，默认先行后列
    column-gap: 1rem; // 列间距
    row-gap: 1rem; // 行间距
    justify-items: center; // 单元格内元素水平位置
    align-items: start; // 单元格内元素垂直位置
  }
}
</style>